<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ajax.练习</title>
    <style>
        li {
            list-style: none;
        }
    </style>
</head>

<body>
    <input type="" name="">
    <button>查询</button>
    <img src="">
    <ul>
    </ul>
</body>

</html>
<script>
    let btn = document.querySelector('button')
    let inp = document.querySelector('input')
    let img = document.querySelector('img')
    btn.onclick = function () {
        let xhr = new XMLHttpRequest()
        xhr.open('get', `https://geoapi.qweather.com/v2/city/lookup?location=${inp.value}&key=c494e264764449f7b4f6bf742276d7f9`)
        xhr.send()
        let ul = document.querySelector('ul')

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                let res = JSON.parse(xhr.responseText)
                let location = res.location
                ul.innerHTML = ''
                for (let i = 0; i < location.length; i++) {
                    let cityId = location[i].id;
                    let weatherXhr = new XMLHttpRequest();
                    weatherXhr.open('get', `https://devapi.qweather.com/v7/weather/now?location=${cityId}&key=c494e264764449f7b4f6bf742276d7f9`);
                    weatherXhr.send();
                    weatherXhr.onreadystatechange = function () {
                        if (weatherXhr.readyState == 4 && weatherXhr.status == 200) {
                            let weatherRes = JSON.parse(weatherXhr.responseText)
                            let weatherNow = weatherRes.now;
                            let li = `<li>名字${location[i].name}---国家${location[i].country}---天气状况${weatherNow.text}---温度${weatherNow.temp}°C</li>`;
                            ul.innerHTML += li;
                            if(res.code == 200){
                                img.src = `https://a.hecdn.net/img/common/icon/202106d/${weatherNow.icon}.png`
                            }
                        }
                    }
                }
            }
        }
    }
</script>